package com.ruoyi.system.interAttr.attr;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.UUIDGenerator;
import com.ruoyi.system.interAttr.domain.GamesRes;
import com.ruoyi.system.interAttr.domain.InterAttrRes;
import com.ruoyi.system.interAttr.domain.InterServerRes;
import com.ruoyi.system.model.domain.SalePartner;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.net.URLEncoder;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 交易游 数据获取
 *
 * @author ruoyi
 * @data 2024/7/1
 * @apiNote
 */
@Slf4j
@Service
public class JIAOYIYOUAttr implements AdapterAttr {
    @Resource
    private RedisCache redisCache;
    private static String SERVICE_NAME = "JIAOYIYOU";

    /**
     * 获取游戏列表
     *
     * @return
     */
    @Override
    public List<GamesRes> getGames(SalePartner salePartner) {
        List<GamesRes> resultList = new ArrayList<>();
        Map<String, Object> params = new HashMap<>();
        String curTime = Long.toString(System.currentTimeMillis() / 1000);
        params.put("appId", salePartner.getSaleKey());
        params.put("CurTime", curTime);//当前时间
        params.put("uri", "/outGood/outside/gameList");//请求uri
        String sign = generate(params, salePartner.getOther());//签名
        params.remove("CurTime");
        params.remove("uri");

        String response = HttpRequest.post("https://jyym.jiaoyiyou.com/outGood/outside/gameList")
                .header("CurTime", String.valueOf(curTime)).header("CheckSum", sign).body(JSONObject.toJSONString(params)).execute().body();
        JSONObject jsonObject = JSONObject.parseObject(response);
        JSONArray jsonArray = jsonObject.getJSONArray("data");
        for (Object json : jsonArray) {
            GamesRes gamesRes = new GamesRes();
            gamesRes.setId(JSONObject.parseObject(json.toString()).getString("game_id"));
            gamesRes.setGameName(JSONObject.parseObject(json.toString()).getString("title"));
            resultList.add(gamesRes);
        }
        return resultList;
    }

    public static void main(String[] args) {

        String response = null;

        if (StringUtils.isEmpty(response)) {
            Map<String, Object> params = new HashMap<>();
            String curTime = Long.toString(System.currentTimeMillis() / 1000);
            params.put("appId", "30e4dfaa3a05f414e11c2322eecac3cf3037bfe98d8cee400cafedc3c43073d6");
            params.put("gameId", "217");
            params.put("CurTime", curTime);//当前时间
            params.put("uri", "/outGood/outside/gameScreen");//请求uri
            String sign = generate(params, "8efcce06f752a708cc73");//签名
            params.remove("CurTime");
            params.remove("uri");
            response = HttpRequest.post("https://jyym.jiaoyiyou.com/outGood/outside/gameScreen")
                    .header("CurTime", String.valueOf(curTime)).header("CheckSum", sign).body(JSONObject.toJSONString(params)).execute().body();
            if (response.contains("12010")) {
                throw new GlobalException(response);
            }
        }

        System.out.println(response);


    }

    /**
     * 获取区服列表
     *
     * @return
     */
    @Override
    public List<InterServerRes> getServer(String gameId, SalePartner salePartner) {
        String key = SERVICE_NAME + "_" + gameId;
        String response = null;

        if (StringUtils.isEmpty(response)) {
            Map<String, Object> params = new HashMap<>();
            String curTime = Long.toString(System.currentTimeMillis() / 1000);
            params.put("appId", salePartner.getSaleKey());
            params.put("gameId", gameId);
            params.put("CurTime", curTime);//当前时间
            params.put("uri", "/outGood/outside/gameScreen");//请求uri
            String sign = generate(params, salePartner.getOther());//签名
            params.remove("CurTime");
            params.remove("uri");
            response = HttpRequest.post("https://jyym.jiaoyiyou.com/outGood/outside/gameScreen")
                    .header("CurTime", String.valueOf(curTime)).header("CheckSum", sign).body(JSONObject.toJSONString(params)).execute().body();
            if (response.contains("12010")) {
                throw new GlobalException(response);
            }
        }

        List<InterServerRes> resultList = new ArrayList<>();
        JSONObject data = JSONObject.parseObject(response).getJSONObject("data");
        List<JSONObject> array = JSONObject.parseArray(data.getString("screen_detail_list"), JSONObject.class);
        for (JSONObject jsonObject : array) {

            if (StringUtils.equals("1", jsonObject.getString("type"))) {
                List<JSONObject> screen_detile_list = JSONObject.parseArray(jsonObject.getString("screen_detile"), JSONObject.class);
                for (JSONObject json : screen_detile_list) {
                    InterServerRes interServerRes = new InterServerRes();
                    interServerRes.setId(json.getString("id"));
                    interServerRes.setName(json.getString("title"));
                    if (CollectionUtils.isNotEmpty(json.getJSONArray("screen_detile"))) {
                        List<InterServerRes> arrayList = new ArrayList<>();
                        List<JSONObject> screen_detile = JSONObject.parseArray(json.getString("screen_detile"), JSONObject.class);
                        for (JSONObject json1 : screen_detile) {
                            InterServerRes res = new InterServerRes();
                            res.setId(json1.getString("id"));
                            res.setName(json1.getString("title"));
                            arrayList.add(res);
                        }
                        interServerRes.setInterServerRes(arrayList);
                    }
                    resultList.add(interServerRes);
                }
                break;
            }
        }

        return resultList;
    }

    /**
     * 获取属性列表
     *
     * @return
     */
    @Override
    public List<InterAttrRes> getPropety(String gameId, String type, SalePartner salePartner) {
        String key = SERVICE_NAME + "_" + gameId;
        String response = null;
        try {
            response = redisCache.getCacheObject(key);
        } catch (Exception e) {
            log.error("redis 读取失败");
        }
        if (StringUtils.isEmpty(response)) {
            Map<String, Object> params = new HashMap<>();
            String curTime = Long.toString(System.currentTimeMillis() / 1000);
            params.put("appId", salePartner.getSaleKey());
            params.put("gameId", gameId);
            params.put("CurTime", curTime);//当前时间
            params.put("uri", "/outGood/outside/gameScreen");//请求uri
            String sign = generate(params, salePartner.getOther());//签名
            params.remove("CurTime");
            params.remove("uri");
            response = HttpRequest.post("https://jyym.jiaoyiyou.com/outGood/outside/gameScreen")
                    .header("CurTime", String.valueOf(curTime)).header("CheckSum", sign).body(JSONObject.toJSONString(params)).execute().body();
            if (response.contains("12010")) {
                throw new GlobalException(response);
            }
        }
        try {
            redisCache.setCacheObject(key, response, 3, TimeUnit.MINUTES);
        } catch (Exception e) {
            log.error("redis 存入失败");
        }
        List<InterAttrRes> resultList = new ArrayList<>();
        JSONObject data = JSONObject.parseObject(response).getJSONObject("data");
        List<JSONObject> array = JSONObject.parseArray(data.getString("screen_detail_list"), JSONObject.class);
        // 1 单选 2 多选 3 输入框    (交易游没有输入框  type3 是区服)
            for (JSONObject jsonObject : array) {
                if (StringUtils.equals("1", jsonObject.getString("type"))) {
                    continue;
                }
                if (StringUtils.equals(jsonObject.getString("from_type"), type)) {
                    JSONArray screen_detile = jsonObject.getJSONArray("screen_detile");
                    InterAttrRes res = new InterAttrRes();
                    res.setUuid(UUIDGenerator.generateUuid6());
                    res.setId(jsonObject.getString("id"));
                    res.setName(jsonObject.getString("title"));
                    if (jsonObject.getInteger("is_must") == 1) {
                        res.setRequired(true);
                    } else {
                        res.setRequired(false);
                    }
                    if (CollectionUtils.isNotEmpty(screen_detile)) {
                        List<InterAttrRes> detileList = new ArrayList<>();
                        for (Object o : screen_detile) {
                            InterAttrRes res1 = new InterAttrRes();
                            res1.setUuid(UUIDGenerator.generateUuid6());
                            JSONObject object = JSONObject.parseObject(o.toString());
                            res1.setId(object.getString("id"));
                            res1.setName(object.getString("title"));
                            if (object.getInteger("is_must") == 1) {
                                res1.setRequired(true);
                            } else {
                                res1.setRequired(false);
                            }
                            detileList.add(res1);

                        }
                        if (CollectionUtils.isNotEmpty(detileList)) {
                            res.setInterServerRes(detileList);
                        }
                    }
                    resultList.add(res);
                }
            }
        return resultList;
    }

    public static String generate(Map<String, Object> params, String appSecret) {
        // 1.删除参数组中所有等值为FALSE的参数
        // 2.按照键名对参数数组进行升序排序
        Map<String, String> paramProcess = new LinkedHashMap<>();
        params.entrySet().stream()
                .filter(x -> !StrUtil.isEmpty(String.valueOf(x.getValue())) && !Arrays.asList("app_secret", "signature").contains(x.getKey()))
                .sorted(Map.Entry.comparingByKey())
                .forEachOrdered(x -> paramProcess.put(x.getKey(), String.valueOf(x.getValue())));

        // 3.给参数数组追加app_secret的值
        paramProcess.put("app_secret", appSecret);
        // 4.生成 URL-encode 之后的请求字符串
        String urlEncode = urlEncode(paramProcess);
        // 5.将请求字符串使用MD5加密后，再转换成大写
        return DigestUtils.md5Hex(urlEncode).toUpperCase();
    }

    public static String urlEncode(Map<String, String> paramProcess) {
        try {
            String urlEncode = "";
            Iterator<Map.Entry<String, String>> it = paramProcess.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<String, String> entry = it.next();
                String key = entry.getKey();
                String value = entry.getValue();

                key = URLEncoder.encode(key, "utf-8");
                key = key.replace("*", "\t%2A");

                value = URLEncoder.encode(value, "utf-8");
                value = value.replace("*", "\t%2A");
                urlEncode += key + "=" + value + "&";
            }
            urlEncode = urlEncode.substring(0, urlEncode.length() - 1);
//            System.out.println("urlEncode=========="+urlEncode);
            return urlEncode;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
